package com.longe.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Netty 使用 websocket
 */
public class NettyWebsocketServer {

    public static void main(String[] args) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //创建服务器端的启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置配置
            serverBootstrap.group(bossGroup, workerGroup) //设置两个线程组
                    .channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务端的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) //设置等待连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //保持活动连接状态
                    //为workerGroup 的 EventLoop 对应的管道设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            //为pipeline添加handler
                            ChannelPipeline pipeline = ch.pipeline();

                            //因为基于http协议，使用http的编码和解码器
                            pipeline.addLast(new HttpServerCodec());
                            //是以块方式写，添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());

                            /**
                            说明
                              1. http数据在传输过程中是分段, HttpObjectAggregator可以将多个段聚合
                              2. 这就就是为什么，当浏览器发送大量数据时，就会发出多次http请求
                             */
                            pipeline.addLast(new HttpObjectAggregator(8192));

                            /**
                            说明
                              1. 对应websocket, 它的数据是以 帧(frame)形式传递
                              2. WebSocketFrame下面有六个子类
                              3. 浏览器请求时 ws://localhost:9999/test 表示请求的uri
                              4. WebSocketServerProtocolHandler 核心功能是将 http协议升级为 ws协议,从而保持长连接
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/test"));

                            //为pipeline添加自己的业务handler
                            pipeline.addLast(new NettyWebsocketHandler());
                        }
                    });

            //绑定端口并同步
            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();

            System.err.println("Netty websocket服务器启动");
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}